/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package code

import (
	"gitee.com/tugoer/param"
	"net/http"
	"fmt"
	"io"
	"encoding/json"
)

// 参数模型
type User struct {
	Name string `param:"name" len:"6-14" len-msg:"6-14个UTF-8字符" desc:"必须在 6-14 个 UTF-8 字符之间, name 未被 required, 因此可为空值"`
	Password string `param:"password"`
}

// 参数模型
type Secure struct {
	Token string `param:"token" required:"不能为空"`
}

// 参数列表
var Parameters = []param.Parameter{
	{In: param.Form, Schema: &User{}},
	{In: param.Query, Schema: &Secure{}},
}

// 注册参数模型
var	parser = param.RegisterParameters(Parameters)

// 处理表单
var FormHandler http.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) {

	// 初始化参数模型
	user := &User{}
	secure := &Secure{}
	// 解析并验证参数
	msg, id, err := parser.ValidAndParseHttp(request, nil, user, secure)
	if err != nil {
		// 检测错误
		http.Error(writer, err.Error(), http.StatusBadRequest)
	} else if msg != "" {
		// 验证未通过
		http.Error(writer, fmt.Sprintf("%s:%s", id, msg), http.StatusBadRequest)
	} else {
		// 验证通过, 响应 json 数据给客户端
		writer.Header().Set("Content-Type", "application/json")
		encoder := json.NewEncoder(writer)
		encoder.SetIndent("", "\t") // 格式化 json 数据
		encoder.Encode(map[string]interface{}{
			"user": user,
			"secure": secure,
		})
	}
}

// html 页面生成器
var HtmlHandler = func(postUrl string) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
	io.WriteString(writer, `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Param Http Example</title>
</head>
<body>
<form action="`+postUrl+`" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name">
    <label for="password">Password:</label>
    <input type="password" name="password" id="password">
	<label for="token">Token:</label>
    <input type="text" name="token" id="token">
    <input type="submit" value="提交">
</form>
</body>
</html>`)
	}
}